define(['../common/common','../common/pathCompute', 'ztree', 'text!../../pages/dataBase/classifyService.html', 'text!../../pages/dataBase/classifyServiceAdd.html', 'text!../../pages/dataBase/materialService.html', './materialService'],function ($, pathfn, ztree, classifyServiceHtml, classifyServiceAddHtml, materialServiceHtml, materialService){
  	var interface =  pathfn.interface,
  		backDataAll = {}, 
  		tableHeight = $(window).height() - $('#budget-header').height() - $('.layui-footer').height() -40;
  	var classifyService = function(popId){
  		if(popId){
  			$('#' + popId.id).html(classifyServiceHtml);
  			$('.projectHideBtn').hide(0);
  		} else{
  			$('.page-content').html(classifyServiceHtml); 
  		}
	    var addDataNodeHtml  =  $(classifyServiceAddHtml)[0],
	    addCostCodeHtml =  $(classifyServiceAddHtml)[2],
	    specificItemHtml = $(classifyServiceAddHtml)[5];
	    console.log($(classifyServiceAddHtml))
	    layui.use([ 'table','form','laypage' ],function() {
          	var table = layui.table,
          	form = layui.form,
          	laypage = layui.laypage;
          	init = function(){  
           	 	ztreeOperateClfy.ztreeInit();
           	 	if(popId){
           	 		tableOperateClfy.tableInit(popId);
           	 	}           	 	
            	bindEvents();
          	},
		    ztreeOperateClfy = {
		      	setting: {
			        async: {
			            enable: true,
			            url: interface.categoryModelList,
			            autoParam:["listCode='COST_CODE'","node=='root'"]
			        }, 
			        data: {
			          	key: {
			            	title: "",
			            	name: 'text'
			          	},
			          	keep: {
							parent:true,
							leaf:true
						},
						simpleData: {
							enable: true
						}
			        },     
			        callback: {
			            onAsyncSuccess: function(event, treeId, treeNode, msg) {
		                    var treeObj = $.fn.zTree.getZTreeObj("tree-list3"),
		                    //获取ztree 所有节点
		                    getNodes = treeObj.getNodes();
		                    //获取ztree 第一个节点
		                    treeObj.selectNode(getNodes[0]);  
		                    //給第一个节点触发点击事件，显示右边table
		                    ztreeOperateClfy.setting.callback.onClick('click','tree-list3',getNodes);
		                    //展开ztree
		                    treeObj.expandAll(true);
		                    $('.content-loading').remove(); 
		                },
		                onClick: function(even, treeId, treeNode) {
		                	var treeNode = treeNode[0] || treeNode;
		                	if(!popId){
		                		!treeNode.leaf ? $('.add-costCode').slideUp(100) : $('.add-costCode').slideDown(100);
		                	}
		                    $('.add-specificItem-show').slideUp(0);
		                    $('#item-table').next('.layui-table-view').remove();
		                    tableOperateClfy.tableInit(even, treeId, treeNode);
		                    //layer.closeAll();
		                }
			        }
			    },
		      	ztreeInit: function(){  //加载左侧菜单树
		        	$.fn.zTree.init($("#tree-list3"), this.setting);  		        			        	
		      	},
		      	addNodeOpen: function(zTree, treeNode, isParent) {  //添加左节点
		      		var _this = this;
		      		var openObj = {
	                  	content: $(addDataNodeHtml).html(),
	                  	title: isParent ? '新增章' : '新增节',
	                  	success: function(layero, index){
		                    form.on('submit(addDataNode)', function(data){
		                      	var formData = data.field,
			                    dataCmd = isParent ? 'newchapter' : 'newpart',
			                    parentId = isParent ? '' : treeNode && treeNode.id;
			                    $.ajaxRequest({
							    	url: interface.updateValue,
							    	data:{
										"cmd": dataCmd,
										"parentId": parentId,
										"code": formData.code,
										"name": formData.name
									},
							    	successfn: function(data) {	
							    		if(isParent && !treeNode.leaf){
							    			zTree.addNodes(null, {children:[],expanded:true,id:'',leaf:false,text:formData.name,isParent:true});
							    			_this.ztreeInit();
							    		}else{
							    			if(treeNode){
							    				zTree.addNodes(treeNode, {children:[],expanded:true,id:'',leaf:false,text:formData.name,isParent:false});
							    				_this.ztreeInit();
							    			}else{
							    				layer.msg('请先选择一章', {
				                        			icon: 5,
											        btn: ['确定']
											    });
							    			}
							    		}
					                    layer.close(index);
							    	}
								})
			                    return false;
		                    });
		                },
		                yes: function(){
	                    	$('.addDataNode').trigger('click');	                    	
	                    }
	                }
	                layerOpenfn(openObj); 
		      	}
			};
			tableOperateClfy = {
				tableInitObj: function(popId){
					var colsHeight = [
						{field:'code', title: '子目编码', width:200, sort: true},
		                {field:'name', title: '子目名称', width:200},
		                {field:'projectProp', title: '项目特征', width:200},
		                {field:'unit', title: '计量单位', width:100, align:'center'},
		                {field:'noPrice', title: '不含税单价', width:150, align:'center'},
		                {field:'price', title: '含税单价', width:150, align:'center'},
		                {field:'transportFee', title: '运输费', width:150, align:'center'},
		                {field:'materialFee', title: '材料费', width:150, align:'center'},
		                {field:'installationFee', title: '安装费', width:150, align:'center'}
			        ];
		            if(popId){
		            	colsHeight.unshift({checkbox: true});
		            }else{
		            	colsHeight.push({field:'caozuo', title: '操作', width:120, align:'center', fixed:'right', toolbar: '#barDemo'});
		           	}
              		var obj = {
	              		id: 'classify-table',
	              		elem: '#classify-table', //指定原始表格元素选择器（推荐id选择器）
	              		height: 'full-335', //容器高度
	              		cols:  [colsHeight],
		              	url: interface.detailCategoryMode,
		              	method: 'get',
		              	page: true, //开启分页
		              	limit: 20, //默认采用60
		              	loading: true
		            }
		            return obj;
              	},
            	tableInit: function(even, treeId, treeNode){
		            var _this = this,
		            defaults = {
		                where: {
		              		param2: treeNode && treeNode.children && treeNode.children.length > 0 ? 'onelevel' : '',
		                	parentId: treeNode && treeNode.id !== '0' && treeNode.id || ''
		              	},
		              	done: function(res, curr, count){
		              		_this.listEdit(_this.tableInitObj()); 
		              	}
		            }
		           	$.extend(true, defaults, _this.tableInitObj(popId));        
		            table.render(defaults);
		            _this.tableEdit();              
		        },
		        tableEdit: function(){
		        	table.on('tool(classifyEvent)', function(obj){
		              	var dataObj = obj.data;
		              	if(obj.event === 'edit'){
			                var openObj = {
			                  	"content": $(addCostCodeHtml).html()+"<script type='text/javascript'>"+$(addCostCodeHtml)[0].nextSibling.innerHTML+"</script>",
			                  	"title":'修改',
			                  	"success": function(layero, index){
				                    layero.find("input[name='code']").val(dataObj.code).attr("readonly","readonly");
				                    layero.find("input[name='name']").val(dataObj.name);
				                    layero.find("input[name='projectProp']").val(dataObj.projectProp);
				                    layero.find("select[name='unit']").val(dataObj.unit);
				                    form.render();
				                    form.on('submit(costCodeFilter)', function(data){
				                      	var formData = data.field;
				                      	$.ajaxRequest({
					                        url: interface.updateValue,
					                        data:{
					                          "cmd": 'editCMUpdate',
					                          "parentId": dataObj.parentId,
					                          "id": dataObj.id,
					                          "code": formData.code,
					                          "name": formData.name,
					                          "unit": formData.unit,
					                          "projectProp": formData.projectProp
					                        },
					                        successfn: function(data) {
					                        	// if (data.success==true) {
			                            //   layer.msg("增加成功");
			                            //   layer.close(layeradd);
			                            // }else{
			                            //   layer.msg(data.msg);
			                            // }
						                        obj.update({
						                            "code": formData.code,
							                        "name": formData.name,
							                        "unit": formData.unit,
							                        "projectProp": formData.projectProp
						                        });
					                        },
					                        errorfn: function(data){
					                          	obj.update({
						                            "code": formData.code,
							                        "name": formData.name,
							                        "unit": formData.unit,
							                        "projectProp": formData.projectProp
						                          });
					                        }
			                      		})
			                      		layer.close(index);
			                      		return false;
			                    	});
			                  	},
			                    "yes": function(){
			                    	$('.costCodeFilter').trigger('click');                    	
			                    }
			                }
		                	layerOpenfn(openObj);
		              	}else if(obj.event === 'detail'){ 
		              		$('.add-specificItem-show').slideDown(100);
		              		backDataAll.unitProject_Id = dataObj.id;
		              		if(!popId){
		              			clildtableOperateClfy.tableInit(dataObj.id);
		              		}
		              		
		              	}
		            });
		        },
		        listEdit: function($obj){
	              var elem = $obj.elem,
	              $caozuo = $(elem).next('.layui-table-view');
	              if(!$caozuo.find('.caozuo-vis').length){
	                pathfn._toggleVisInit($obj.cols,$obj.elem,function(){
	                  form.render();
	                });
	              }else{
	                var inputArr = $caozuo.find('.caozuo-vis').find("input[type='checkbox']");
	                for(var i=0; i< inputArr.length; i++){
	                  var ischecked = inputArr.eq(i).prop('checked'),
	                    field = $(inputArr[i]).data('field');
	                  if(ischecked){                
	                    $caozuo.find('td[data-field="'+field+'"],th[data-field="'+field+'"]').hide(0);
	                  }else{
	                    $caozuo.find('td[data-field="'+field+'"],th[data-field="'+field+'"]').show(0);
	                  }
	                }
	              }
	            }      
			};
			clildtableOperateClfy = {
				tableInitObj: function(){
              		var obj = {
		              id: 'item-table',
		              elem: '#item-table', //指定原始表格元素选择器（推荐id选择器）
		              height: 'full-335', //容器高度
		              cols:  [[ //标题栏
		                // {field:'no', title: '序号', width:100, sort: true, align:'center'},
		                {field:'code', title: '编码', width:200, sort: true},
		                {field:'name', title: '名称', width:200},		                
		                {field:'unit', title: '单位', width:100, align:'center'},
		                {field:'scrapRate', title: '损耗率', width:200},
		                {field:'baseContent', title: '基本含量', width:200},
		                {field:'amount', title: '含量', width:200},
		                {field:'noPrice', title: '不含税单价', width:150, align:'center'},
		                {field:'price', title: '含税单价', width:150, align:'center'},
		                {field:'rate', title: '税率', width:150, align:'center'},
		                {field:'sumNoPrice', title: '不含税合价', width:150, align:'center'},
		                {field:'sumPrice', title: '含税合价', width:150, align:'center'},
		                {field:'caozuo', fixed: 'right', title: '操作', width:80, align:'center', fixed:'right', toolbar: '#item-barDemo'}
		              ]],
		              url: interface.queryDetailYCA,
		              method: 'get',
		              page: false, //开启分页
		              limit: 10000, //默认采用60
		              loading: true              
		            }
              		return obj;
              	},
              	tableInit: function(unitProjectId){
		            var _this = this,
		            defaults = {
		            	where: {
			              	unitProject_Id: unitProjectId,
			              	start: 0
			            },
			            done: function(res, curr, count){
			              	_this.listEdit(_this.tableInitObj()); 
			            }
		            }
		           	$.extend(true, defaults, _this.tableInitObj());        
		            table.render(defaults);
		            _this.tableEdit();              
		        },
		        tableEdit: function(){
		        	table.on('tool(specificItemEvent)', function(obj){    //点击子目里的修改按钮
		              	var dataObj = obj.data;
		              	if(obj.event === 'edit'){
			                var openObj = {
			                  	"content": $(specificItemHtml).html(),
			                  	"title":'运材安维护',
			                  	"success": function(layero, index){
				                    layero.find("input[name='ycaName']").val(dataObj.name).attr("readonly","readonly");
				                    layero.find("input[name='scrapRate']").val(dataObj.scrapRate);
				                    layero.find("input[name='baseContent']").val(dataObj.baseContent);
				                    form.render();
				                    $('.addTableDetails').hide(0);
				                    
				                    form.on('submit(specificItemFilter)', function(data){
				                      	var formData = data.field;
				                      	$.ajaxRequest({
					                        url: interface.updateValue,
					                        data:{
					                          "cmd": 'edit',
					                          "unitProject_Id": dataObj.unitProject_Id,
					                          "parentId": dataObj.parentId,
					                          "id": dataObj.id,
					                          "ycaName": formData.ycaName,
					                          "content": formData.baseContent,
					                          "scrapRate": formData.scrapRate,
					                          "baseContent": formData.baseContent
					                        },
					                        successfn: function(data) {
					                        	// if (data.success==true) {
				                            //   layer.msg("增加成功");
				                            //   layer.close(layeradd);
				                            // }else{
				                            //   layer.msg(data.msg);
				                            // }
						                        obj.update({
						                            "baseContent": formData.baseContent,
						                            "scrapRate": formData.scrapRate,
						                            "ycaName": formData.ycaName
						                        });
					                        },
					                        errorfn: function(data){
					                          	obj.update({
						                            "baseContent": formData.baseContent,
						                            "scrapRate": formData.scrapRate,
						                            "ycaName": formData.ycaName
						                        });
					                        }
			                      		})
			                      		layer.close(index);
			                      		return false;
			                    	});
			                  	},
			                    "yes": function(){
			                    	$('.specificItemFilter').trigger('click');                    	
			                    }
			                }
		                	layerOpenfn(openObj);
		              	}  
		            });
		        },
		        listEdit: function($obj){
	              var elem = $obj.elem,
	              $caozuo = $(elem).next('.layui-table-view');
	              if(!$caozuo.find('.caozuo-vis').length){
	                pathfn._toggleVisInit($obj.cols,$obj.elem,function(){
	                  form.render();
	                });
	              }else{
	                var inputArr = $caozuo.find('.caozuo-vis').find("input[type='checkbox']");
	                for(var i=0; i< inputArr.length; i++){
	                  var ischecked = inputArr.eq(i).prop('checked'),
	                    field = $(inputArr[i]).data('field');
	                  if(ischecked){                
	                    $caozuo.find('td[data-field="'+field+'"],th[data-field="'+field+'"]').hide(0);
	                  }else{
	                    $caozuo.find('td[data-field="'+field+'"],th[data-field="'+field+'"]').show(0);
	                  }
	                }
	              }
	            }
			};  
			bindEvents = function(){
	      		$('#addDataNode').bind("click", function(e){
	      			debugger
	      			var zTree = $.fn.zTree.getZTreeObj("tree-list3"),
	      			nodes = zTree.getSelectedNodes();
					treeNode = nodes[0];
					if(treeNode && treeNode.leaf){
						layer.msg('节是不能添加章节的！', {
                			icon: 5,
					        btn: ['确定']
					    });
					}else{
						$(this).find('.addNodeList').slideDown(200)
					}	

				})
				$('.add-node').each(function(index, el) {
					$(this).bind("click", function(event){
						event.stopPropagation();			
						var _this = this,
						isParent = eval($(_this).attr('isParent')), //判断添加章还是节
						zTree = $.fn.zTree.getZTreeObj("tree-list3"),
						nodes = zTree.getSelectedNodes();
						treeNode = nodes[0];
						ztreeOperateClfy.addNodeOpen(zTree, treeNode, isParent);
						$(_this).parents('.addNodeList').eq(0).slideUp(200);
					})
				});
				$('.add-costCode').click(function(){  //点击上方新增
	                var treeObj = $.fn.zTree.getZTreeObj("tree-list3"),
	                	selectedNodes = treeObj.getSelectedNodes();
	                var openObj = {
	                  	"content": $(addCostCodeHtml).html()+"<script type='text/javascript'>"+$(addCostCodeHtml)[0].nextSibling.innerHTML+"</script>",
	                  	"title":'新增',
	                  	"success": function(layero, index){
	                  		form.render();
	                    	form.on('submit(costCodeFilter)', function(data){
	                      		var formData = data.field;
	                      		
		                      	$.ajaxRequest({
			                        url: interface.updateValue,
			                        data:{
			                          "cmd": 'editCM',
			                          "parentId": selectedNodes[0].id,
			                          "id":  '',
			                          "code": formData.code,
			                          "name": formData.name,
			                          "unit": formData.unit,
			                          "projectProp": formData.projectProp
			                        },
			                        successfn: function(data) {	
			                        	if((!data.success && data.code == 'undefined') || (data.success == 'undefined' && data.code)){
			                        		layer.msg(data.msg, {
			                        			icon: 5,
											    btn: ['确定']
											});
			                        	}else{
			                        		table.reload('classify-table');
			                          		layer.close(index);
			                        	}
			                          	
			                        },
			                        errorfn: function(data) {
			                          	table.reload('classify-table');
			                        }
		                      	})
		                      	return false;
	                    	})
	                  	},
	                    "yes": function(){
	                    	$('.costCodeFilter').trigger('click');
	                    }
	                }
	                layerOpenfn(openObj);                 
	            })         
	            $('.add-specificItem').click(function(){      //点击子目里的新增按钮
	                var openObj = {
	                  	"content": $(specificItemHtml).html(),
	                  	"title":'新增运材安',
	                  	"success": function(layero, index){
	                  		form.render();
	                  		$('.addTableDetails').show(0);
	                    	form.on('submit(specificItemFilter)', function(data){
	                    		var data = data.field;
	                    		backDataAll.cmd = 'new';
	                    		backDataAll.id = '';
	                    		backDataAll.ycaName = data.ycaName;
								backDataAll.content = data.baseContent;
								backDataAll.scrapRate = data.scrapRate;
								backDataAll.baseContent =  data.baseContent;
		                      	$.ajaxRequest({
			                        url: interface.updateValue,
			                        data:backDataAll,
			                        successfn: function(data) {			                        	
			                        	if(!data.success){
			                        		layer.msg(data.msg, {
			                        			icon: 5,
										        btn: ['确定']
										    });
			                        	}else{
			                        		table.reload('item-table');
			                          		layer.close(index);
			                        	}
			                          	
			                        },
			                        errorfn: function(data) {
			                          	table.reload('item-table');
			                        }
		                      	})
		                      	return false;
	                    	})
	                  	},
	                    "yes": function(){
	                    	$('.specificItemFilter').trigger('click');
	                    }
	                }
	                layerOpenfn(openObj);                 
	            })
	            $(document).on("click", ".addTableDetails",function(){  //点击子目中的新增添加子目运材安
					var $this = $(this);
					var openObj = {
	                  	content: materialServiceHtml,
	                  	title:'运材安维护',
	                  	id:'materialServicePop',
	                  	area:  ['90%', '90%'],
	                  	success: function(layero, index){
	                  		materialService({id:'materialServicePop'});
	                  		console.log(1)
	                  		return false;
	                  	},
	                    yes: function(index,layero){
	                    	var checkStatus = table.checkStatus('material-table')
      						,data = checkStatus.data; 
      						if(!data.length || data.length > 1){
      							layer.msg('只能选择一条数据', {
                        			icon: 5,
							        btn: ['确定']
							    });
      						}else{
      							data = data[0];
      							$('.specificItem').find('input[name="ycaName"]').val(data.name); 
      							backDataAll.ycaModelId = data.id;
      							layer.close(index);
      						}
	                    }
	                }
                	layerOpenfn(openObj);
								
				});
				form.verify({
				    decimal: function(value){
				    	var reg = /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/;
				    	if(!reg.test(value)){
				        	return '分值必须是非负数字';
				     	}
				    },
				    code: function(value){
				    	var reg = /^(\d+)(-)(\d+)(-)(\d+)$/;
				    	if(!reg.test(value)){
				    		return '分值必须是数字-数字-数字的类型';
				    	}
				    }
				});
	      	};
	        layerOpenfn = function(openObj){
	            layer.open({
	            	type: openObj.type || 1,
	                content: openObj.content || '',
	                title: openObj.title || '',
	                btn: ['确定','取消'],
	                area: openObj.area || '450px',
	                skin: 'lay-padding',
	                id: openObj.id || '',
	                scrollbar : true,
	                success: function(layero, index){
	                  	openObj.success(layero, index);
	                },
	                yes: function(index,layero){
	                  openObj.yes(index,layero);
	                },
	                btn2 : function(index, layero) {
					}
	            });
	        };
		    init();
		})
	}
  	return classifyService;
})
